package org.conditure.web.http;

import java.io.IOException;
import java.net.URLDecoder;

import com.google.common.base.Strings;

/**
 * Represents an HTTP request.
 * 
 * @author Elvir
 */
public class HttpRequest extends HttpPayload {
	protected HttpRequestType requestType = HttpRequestType.GET;
	protected String path = "/";
	protected String version = "HTTP/1.1";
	
	/**
	 * Creates an empty HTTP request.
	 */
	public HttpRequest() {
		super();
	}

	/**
	 * Loads the request header line.
	 * 
	 * @throws IOException 
	 * 
	 * @see org.conditure.web.http.HttpPayload#processFirstHeaderLine(java.lang.String)
	 */
	protected void setFirstHeaderLine(String line) throws IOException {
		String[] split = line.split(" ", 3);
		
		if (split.length == 3) {
			requestType = HttpRequestType.valueOf(split[0].trim().toUpperCase());
			path = URLDecoder.decode(split[1], "UTF8");
			version = split[2];
		} else {
			throw new IOException("Unable to parse first header line.");
		}
	}
	
	/**
	 * Constructs the first header line.
	 * 
	 * @see org.conditure.web.http.HttpPayload#getFirstHeaderLine(java.lang.String)
	 */
	protected String getFirstHeaderLine() {
		return String.format("%s %s %s", requestType.name(), path, version);
	}
	
	/**
	 * @return the requestType
	 */
	public HttpRequestType getRequestType() {
		return requestType;
	}

	/**
	 * @param requestType the requestType to set
	 */
	public void setRequestType(HttpRequestType requestType) {
		if (requestType == null) {
			throw new IllegalArgumentException("Request type cannot be null");
		}
		
		this.requestType = requestType;
	}

	/**
	 * @return the path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * @param path the path to set
	 */
	public void setPath(String path) {
		if (Strings.isNullOrEmpty(path)) {
			throw new IllegalArgumentException("Path be null or empty");
		}
		
		this.path = path;
	}

	/**
	 * @return the version
	 */
	public String getVersion() {
		return version;
	}

	/**
	 * @param version the version to set
	 */
	public void setVersion(String version) {
		if (Strings.isNullOrEmpty(version)) {
			throw new IllegalArgumentException("Version cannot be null or empty");
		}
		
		this.version = version;
	}
}
